import os
from datetime import datetime

import oss2
from anthropic import BaseModel
from fastapi import APIRouter, Depends, Form, UploadFile
from sqlalchemy.orm import Session
from database.config import get_db
from models.model import *
from models.base import *
from utils.jwt import create_access_token
from utils.deps import verify_token
router = APIRouter()

class UserAuth(BaseModel):
    username: str
    password: str

# 注册
@router.post('/register')
async def register(user: UserAuth,db : Session = Depends(get_db)):
    new_User = User(username=user.username,password=user.password,create_time=datetime.now())
    db.add(new_User)
    db.commit()
    db.refresh(new_User)
    return Success()

# 登录
@router.post('/login')
async def login(user: UserAuth,db : Session = Depends(get_db)):
    u = db.query(User).filter((User.username == user.username) & (User.password == user.password)).first()
    if u is not None:
        avatar = u.avatar
        token = create_access_token({"username":user.username})
        print(token)
        res_data = {
            "token": token,
            "user_info":{
                "user_id":u.id,
                "username":user.username,
                "avatar":avatar,
            }
        }
        return Success(code = 200,msg = "登录成功",res_data = res_data)
    else:
        return Fail(msg = "登录失败")

# 退出
@router.get('/logout')
async def logout():
    return Success()

# 个人中心接口
@router.get("/user/info")
async def get_user_info(currentUser: dict = Depends(verify_token),
                        db : Session = Depends(get_db)):
    username = currentUser["username"]
    user = db.query(User).filter(User.username == username).first()
    res_data = {
        "avatar": user.avatar,
        "username": username,
        "intention_position": user.position,
        "static_info": {
            "interview_num": user.interview_num,
            "answer_num": user.answer_num,
            "interview_time": user.interview_time
        }
    }
    return Success(code=200, msg="success", res_data=res_data)

# 视频学习记录
@router.get("/user/learn_history")
async def get_user_interview(currentUser: dict = Depends(verify_token),db: Session = Depends(get_db)):
    username = currentUser["username"]
    videoList = db.query(LearnHistory).filter(LearnHistory.username == username).all()
    video_history_list = []
    for videoItem in videoList:
        id = videoItem.video_id
        video = db.query(Video).filter(Video.video_id == id).first()
        video_history_list.append({
            "video":{
                "video_name": video.video_name,
                "video_id": id,
                "video_author": video.video_author,
                "video_publish_time": video.video_publish_time.strftime("%Y-%m-%d"),
                "video_pic": video.video_pic,
            },
            "watch_history_time": videoItem.watch_history_time.strftime("%Y-%m-%d")
        })
    res_data = {
        "video_history_list":video_history_list
    }
    return Success(code=200, msg="success", res_data=res_data)

# 发表帖子和收藏帖子
@router.get("/user/post")
async def get_user_post(currentUser: dict = Depends(verify_token),db: Session = Depends(get_db)):
    username = currentUser["username"]

    # 发表帖子
    mypostList = db.query(Post).filter(Post.post_author == username).all()
    my_post_list = []
    for post in mypostList:
        my_post_list.append({
            "post_id": post.post_id,
            "post_title": post.post_title,
            "post_author": post.post_author,
            "post_author_avatar": post.post_author_avatar,
            "post_publish_time": post.post_publish_time.strftime("%Y-%m-%d"),
            "post_abstract": post.post_abstract,
            "post_pic": post.post_pic,
            "post_like_num": post.post_like_num,
            "post_comment_num": post.post_comment_num
        })

    # 收藏帖子
    favorList = db.query(Post).join(PostFavor, Post.post_id == PostFavor.post_id).filter(PostFavor.username == username).all()
    my_favor_list = []
    for post in favorList:
        my_favor_list.append({
            "post_id": post.post_id,
            "post_title": post.post_title,
            "post_author": post.post_author,
            "post_author_avatar": post.post_author_avatar,
            "post_publish_time": post.post_publish_time.strftime("%Y-%m-%d"),
            "post_abstract": post.post_abstract,
            "post_pic": post.post_pic,
            "post_like_num": post.post_like_num,
            "post_comment_num": post.post_comment_num
        })
    res_data = {
        "my_post_list": my_post_list,
        "favor_list": my_favor_list
    }
    return Success(code=200, msg="success", res_data=res_data)

# 面试记录
@router.get("/user/interview")
async def get_user_interview(currentUser: dict = Depends(verify_token),
                             db: Session = Depends(get_db)):
    username = currentUser["username"]

    interview_times = []
    professional_knowledge = []
    adaptability = []
    skill_match = []
    innovation = []
    communication = []
    logical_thinking = []

    interview_evaluation_list = []
    interviewRecords = db.query(InterviewRecord).filter(InterviewRecord.username == username).order_by(InterviewRecord.id.asc()).all()
    for interviewRecord in interviewRecords:
        time = interviewRecord.interview_time.strftime("%Y-%m-%d")
        interview_times.append(time)
        professional_knowledge.append(interviewRecord.professional_knowledge)
        adaptability.append(interviewRecord.adaptability)
        skill_match.append(interviewRecord.skill_match)
        innovation.append(interviewRecord.innovation)
        communication.append(interviewRecord.communication)
        logical_thinking.append(interviewRecord.logical_thinking)

        interview_evaluation_list.append({
            "evaluate_time": time,
            "evaluation": interviewRecord.evaluation
        })

    res_data = {
        "interview_chart": {
            "interview_times": interview_times,
            "professional_knowledge": professional_knowledge,
            "adaptability": adaptability,
            "skill_match": skill_match,
            "innovation": innovation,
            "communication": communication,
            "logical_thinking": logical_thinking
        },
        "interview_evaluation_list": interview_evaluation_list
    }
    return Success(code=200, msg="success", res_data=res_data)

# 获取项目根目录
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(current_dir, "..", "..", ".."))
# 阿里云配置
accessKeyID = 'LTAI5tC1ZV6SDscoPQZr7QsY'
accessKeySecret = 'zByBtNvjtNBIKhzr7cBnKF4zhIWatg'
auth = oss2.Auth(accessKeyID, accessKeySecret)
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
bucketName = "spark-agent"
bucket = oss2.Bucket(auth, endpoint, bucketName, region=region)

# 编辑个人信息
@router.post("/user/edit")
async def user_edit(
        avatar: UploadFile = None,
        username: str = Form(None),
        password: str = Form(None),
        currentUser: dict = Depends(verify_token),
        db: Session = Depends(get_db)):
    preUsername = currentUser["username"]
    user = db.query(User).filter(User.username == preUsername).first()

    # 修改用户信息
    if username is not None:
        user.username = username
    if password is not None:
        user.password = password

    # 保存用户头像
    if avatar.filename is not "":
        # print(avatar)
        # print(avatar.filename)
        file_extension = os.path.splitext(avatar.filename)[1]  # 获取原始扩展名
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        avatarFilename = f"avatar_{timestamp}{file_extension}"
        # 构建保存路径
        save_dir = os.path.join(project_root, "uploadFile")
        os.makedirs(save_dir, exist_ok=True)
        avatar_save_path = os.path.join(save_dir, avatarFilename)

        with open(avatar_save_path, "wb") as f:
            content = await avatar.read()  # 读取文件内容
            f.write(content)  # 将文件内容写入到本地文件中

        # 上传至阿里云oss
        oss_img_key = f"avatar/{avatarFilename}"
        bucket.put_object_from_file(oss_img_key, avatar_save_path)
        avatar_url = f"https://spark-agent.oss-cn-hangzhou.aliyuncs.com/avatar/{avatarFilename}"
        user.avatar = avatar_url
        print(avatar_url)

    db.commit()
    res_data = {
        "username": user.username,
        "avatar": user.avatar
    }
    return Success(code=200, msg="success", res_data=res_data)
